/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AssetRecordFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.presenter.AssetRecordFragmentPresenter;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.utils.DateUtils;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.bean.RecordBeanResponse;

public class AssetRecordFragment extends BaseFragment<AssetRecordFragmentPresenter,AssetRecordFragmentPresenter.AssetRecordFragmentUI> implements AssetRecordFragmentPresenter.AssetRecordFragmentUI, BaseQuickAdapter.RequestLoadMoreListener, BaseFragment.NotifyActivity {

    private RecyclerView recyclerView;
    private int tabType;
    private RecordAdapter adapter;
    private View emptyView;
    private String tokenId;
    public static String KEY_ASSET_TOKENID = "tokenId";

    @Override
    protected AssetRecordFragmentPresenter.AssetRecordFragmentUI getUI() {
        return this;
    }

    @Override
    protected AssetRecordFragmentPresenter createPresenter() {
        return new AssetRecordFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.acitivity_asset_record_fragment,null,false);
    }


    @Override
    protected void initViews() {
        super.initViews();
        Bundle arguments = getArguments();
        if (arguments != null) {
            tabType = arguments.getInt(AppData.INTENT.KEY_RECORD_TYPE, 0);
            tokenId = arguments.getString(KEY_ASSET_TOKENID);
            getPresenter().getRecord(tabType,tokenId,false);
        }
        LinearLayout rootView = viewFinder.find(R.id.rootView);
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        emptyView = layoutInflater.inflate(R.layout.empty_layout, rootView, false);
        recyclerView = viewFinder.find(R.id.recyclerView);

        setOnNotifyActivity(this);
    }

    @Override
    public void showRecordList(List<RecordBeanResponse.RecordItem> datas) {
        if(datas == null)
            return;

        if (adapter == null) {

            adapter = new RecordAdapter(datas);
            adapter.isFirstOnly(false);
            adapter.setOnLoadMoreListener(this,recyclerView);
            adapter.setEnableLoadMore(true);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    RecordBeanResponse.RecordItem item = (RecordBeanResponse.RecordItem) adapter.getItem(position);
                    if (item != null) {
                        IntentUtils.goAssetWithdrawDetail(getActivity(),tabType, item);
                    }
                }
            });
//            swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
//            swipeRefresh.setOnRefreshListener(this);

            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            adapter.setEmptyView(emptyView);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setNewData(datas);
        }
    }

    @Override
    public void onLoadMoreRequested() {
            getPresenter().loadMore(tabType, tokenId,true);
    }
    @Override
    public void loadComplete() {
        if (adapter != null) {
            adapter.loadMoreComplete();
        }
    }

    @Override
    public void loadEnd() {
        if (adapter != null) {
            adapter.loadMoreEnd();
        }
    }

    @Override
    public void loadFailed() {
        if (adapter != null) {
            adapter.loadMoreFail();
        }
    }

    @Override
    public void onNotifyActivity() {
        if(getPresenter() != null)
            getPresenter().getRecord(tabType,tokenId,false);
    }

    @Override
    protected void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (visible) {
            refresh();
        }
    }

    public void refresh(){
        if(getPresenter() != null){
            getPresenter().getRecord(tabType,tokenId,false);
        }
    }

    private class RecordAdapter extends BaseQuickAdapter<RecordBeanResponse.RecordItem,BaseViewHolder> {


        RecordAdapter(List<RecordBeanResponse.RecordItem> data) {
            super(R.layout.item_asset_token_record_layout, data);
        }

        @Override
        protected void convert(final BaseViewHolder baseViewHolder, final RecordBeanResponse.RecordItem itemModel) {
            String quantity = itemModel.getQuantity();
            if (tabType == 0) {
                quantity = "+"+quantity;
                baseViewHolder.setText(R.id.item_asset_record_type, itemModel.getStatusDesc() + "(" + itemModel.confirmNum + "/" + itemModel.requiredConfirmNum + ")");
            }else if(tabType ==1){
                quantity = "-"+quantity;
                baseViewHolder.setText(R.id.item_asset_record_type, itemModel.getStatusDesc());
            }
            baseViewHolder.setVisible(R.id.item_divider, baseViewHolder.getAdapterPosition() != mData.size());
            //baseViewHolder.setVisible(R.id.item_asset_record_detail, true);
            baseViewHolder.setText(R.id.item_asset_record_amount, quantity);
            baseViewHolder.setText(R.id.item_asset_record_time, DateUtils.getSimpleTimeFormat(Long.valueOf(itemModel.getTime()), "HH:mm:ss yyyy/MM/dd"));
            baseViewHolder.setGone(R.id.btnCancel,itemModel.isCanBeCancelled());
            baseViewHolder.getView(R.id.btnCancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DialogUtils.showDialog(mContext, mContext.getResources().getString(R.string.string_reminder), mContext.getResources().getString(R.string.string_comfirm_cancel_withdraw_tips), mContext.getResources().getString(R.string.string_sure), mContext.getResources().getString(R.string.string_cancel), false, new DialogUtils.OnButtonEventListener() {
                        @Override
                        public void onConfirm() {
                            cancelWithdraw(itemModel.getOrderId());
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
                }
            });
        }

    }

    private void cancelWithdraw(String orderId) {
        AssetApi.RequstCancelWithdraw(orderId,new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (response.isSuccess()) {
                        ToastUtils.showLong(getActivity().getResources().getString(R.string.string_cancel_success));
                        refresh();
                    }else{
                        ToastUtils.showLong(getActivity().getResources().getString(R.string.string_cancel_failed));
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }
}
